package com.gigi.exception;

import cn.hutool.core.util.StrUtil;
import com.alibaba.cola.dto.Response;
import com.gigi.model.enums.ErrorCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 全局处理业务异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public Response businessExceptionHandler(BusinessException e) {
        log.error("业务异常：", e);
        return Response.buildFailure(e.getErrCode(), e.getMessage());
    }

    /**
     * 全局处理运行时异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    public Response runtimeExceptionHandler(RuntimeException e) {
        log.error("运行时异常：", e);
        return Response.buildFailure(ErrorCodeEnum.BIZ_EXCEPTION.getErrCode(), StrUtil.format("{}: {}",
                ErrorCodeEnum.BIZ_EXCEPTION.getErrDesc(), e.getMessage()));
    }

    /**
     * 全局处理参数绑定异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Response bindExceptionHandler(MethodArgumentNotValidException e) {
        log.error("参数绑定异常：", e);
        List<String> fieldErrors =
                e.getBindingResult().getFieldErrors().stream().map(FieldError::getDefaultMessage).collect(Collectors.toList());
        return Response.buildFailure(ErrorCodeEnum.PARAM_ERROR.getErrCode(), StrUtil.format("{}: {}",
                ErrorCodeEnum.PARAM_ERROR.getErrDesc(), StrUtil.join(", ", fieldErrors)));
    }

}
